package com.zhoug.common3.utils;

import android.annotation.SuppressLint;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;

/**
 * 解决View设置setFocusableInTouchMode(true) 和setFocusable(true)后单击事件需要点击2次才生效的问题
 * 原因:第一次获取焦点,第二次才触发事件
 *
 * @Author: zhoug
 * @Date: 2024-07-22
 * @Description:
 */
public class FocusClickHelper {

    /**
     * 解决View设置setFocusableInTouchMode(true) 和setFocusable(true)后单击事件需要点击2次才生效的问题
     * @param view
     */
    public static void  bind(View view) {
        if (view == null) return;
        GestureDetector gestureDetector = new GestureDetector(view.getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(@NonNull MotionEvent e) {
                return view.performClick();
            }
            @Override
            public void onLongPress(@NonNull MotionEvent e) {
                view.performLongClick();
            }
        });

        view.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean b = gestureDetector.onTouchEvent(event);
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        if (view.isFocusable() && view.isFocusableInTouchMode() && !view.isFocused()) {
                            view.requestFocus();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        return true;
                }
                return b;
            }
        });

    }

}
